package cn.edu.stu.syllabus.repository.library.remote;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

import cn.edu.stu.syllabus.api.LibraryApi;
import cn.edu.stu.syllabus.repository.library.BookConverter;
import cn.edu.stu.syllabus.repository.library.LibraryDataSource;
import cn.edu.stu.syllabus.repository.library.LibrarySearchInfo;
import cn.edu.stu.syllabus.repository.library.local.BooksResultEntry;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by daidaijie on 2017/3/27.
 */

public class LibraryRemoteDataSource implements LibraryDataSource {

    LibraryApi mLibraryApi;


    public LibraryRemoteDataSource(LibraryApi libraryApi) {
        mLibraryApi = libraryApi;
    }

    @Override
    public Observable<BooksResultEntry> getBooksResult(LibrarySearchInfo librarySearchInfo, int start, int pageNum) {
        Map<String, String> queryMap;

        try {
            queryMap = librarySearchInfo.getQueryMap();
        } catch (UnsupportedEncodingException e) {
            return Observable.error(new Throwable("解析关键字出错"));
        }

        queryMap.put("dp", pageNum + "");
        queryMap.put("page", start + "");

        return mLibraryApi.getLibrary(queryMap)
                .observeOn(Schedulers.computation())
                .map(new Func1<String, BooksResultEntry>() {
                    @Override
                    public BooksResultEntry call(String s) {
                        BooksResultEntry booksResultEntry = BookConverter.convert(s);
                        return booksResultEntry;
                    }
                });
    }

    @Override
    public boolean isSourceEmpty(Throwable errMsg) {
        return errMsg.getClass().getSimpleName().equals("NullPointerException");
    }
}
